package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.widget.EditText;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.UserDao;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.CorrectRespEvent;
import com.hangzhou.xyj.model.type.ECorrectType;
import com.hangzhou.xyj.net.handler.UpdateTeacherHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.UpdateTeacherReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.ToastUtil;


/**
 * Created by Administrator on 2016/1/13.
 */
public class MyCorrectTeacherActivity extends BaseActivity {
    public static final int SUCCESS = 1;
    EditText mEtTeacher;
    Intent intent;

    @Override
    public void initTop() {
        enableTitle(true, "师从");
        enableRightNav(true, "确定");
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_correct_name);

    }

    @Override
    public void initViews() {
        mEtTeacher = (EditText) findViewById(R.id.et_name);


    }

    @Override
    public void initDatas() {
        intent = getIntent();
        mEtTeacher.setText(intent.getStringExtra("value"));
        mEtTeacher.setSelection(mEtTeacher.length());

    }

    @Override
    public void initListeners() {
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                String name = mEtTeacher.getText().toString().trim();
                updateTeacher(name);
            }
        });
    }

    public void updateTeacher(final String teacherName) {
        UpdateTeacherReq updateTeacherReq = new UpdateTeacherReq(Integer.valueOf(CommonPreferences.getUserId(mContext)), teacherName);
        HttpLoader.getInstance().sendRequest(new UpdateTeacherHandler(updateTeacherReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                if ((Boolean) model) {
                    //更新应用中的信息
                    XYJApplication.getUserInfo().setTeacher(teacherName);
                    //更新本地数据库中的信息
                    UserDao dao = new UserDao(mContext);
                    dao.addUser(XYJApplication.getUserInfo());
                    //提示成功
                    ToastUtil.show("保存成功！");
                    CorrectRespEvent event = new CorrectRespEvent();
                    event.setValue(teacherName);
                    event.setTag(ECorrectType.TEACHER.getValue());
                    EventBusUtil.postEvent(event);
                    closeActivity();
                }
            }
        }, 0));
    }
}
